<template>
  <w-dailog
		v-model="dialogVisible"
		width="1100px"
		title="导入生产计划"
		heightFullscreen
		:showMoreBtn="false"
	>
		<div class="fx-import">
				<div class="list-container">
			<div class="header">
        <el-form size="mini" inline label-width="100px">
          <el-form-item label="选择生产计划" class="fx-block-title">
					<el-date-picker
						v-model="dateRange"
						type="daterange"
						range-separator="至"
						start-placeholder="开始日期"
						end-placeholder="结束日期"
						format="yyyy 年 MM 月 dd 日"
						value-format="yyyy-MM-dd"
						class="form-date-input"
					></el-date-picker>
					</el-form-item>
        </el-form>
      </div>
			<w-table
				ref="listTableUnImport"
				:showColumnFilterBtn="false"
				minWidth="100px"
				class="listTable"
        :showPagination="false"
        :tableColumn="tableColumn"
        :listData="filterAllItems"
        :expandRowSlot="true"
				:selectedRows.sync="listSelRows"
			>
        <template slot="row-expand" slot-scope="scope">
          <w-table
							:ref="`listTableUnImportDetail${scope.$index}`"
							:showColumnFilterBtn="false"
							minWidth="100px"
							:minHeight="`${(scope.row.detailList.length + 1) * 45}px`"
							class="listTable"
							:showTools="false"
							:showPagination="false"
							:tableColumn="detailsColumn"
							:listData="scope.row.detailList"
							:selectedRows.sync="scope.row.detailSelRows"
							@onTableRowSelect="onTableRowSelect"
							@onTableRowAllSelect="onTableRowAllSelect"
						>
						</w-table>
        </template>
				<div slot="search-tools-left" class="tools-left" style="width: 310px;">
					<el-input
						placeholder="请输入内容"
						prefix-icon="el-icon-search"
						size="mini"
						v-model="keyWords"
					>
					</el-input>
				</div>
        <div slot="btn-tools-right">
					<el-button class="order-btn" type="primary" size="mini">查询</el-button>
					<el-button class="order-btn" type="text" size="mini" @click="resetSearch">重置</el-button>
				</div>
			</w-table>
				</div>
				<div class="tools-container">
				</div>
				<div class="list-container">
			<div class="header">
        <el-form size="mini" inline label-width="100px">
          <el-form-item label="已选生产计划" class="fx-block-title"></el-form-item>
        </el-form>
      </div>
			<w-table
				ref="listTableSelect"
				:showColumnFilterBtn="false"
				minWidth="100px"
				class="listTable"
        :showPagination="false"
        :tableColumn="tableColumn"
        :listData="filterSelItem"
        :expandRowSlot="true"
				:selectable="false"
			>
				<template slot="row-expand" slot-scope="scope">
          <w-table
							:ref="`listTableSelectDetail${scope.$index}`"
							:showColumnFilterBtn="false"
							minWidth="100px"
							:minHeight="`${(scope.row.detailList.length + 1) * 45}px`"
							class="listTable"
							:showTools="false"
							:showPagination="false"
							:selectable="false"
							:tableColumn="detailsColumn"
							:listData="scope.row.detailList"
						>
						</w-table>
        </template>
				<div slot="search-tools-left" class="tools-left" style="width: 310px;">
					<el-input
						placeholder="请输入内容"
						prefix-icon="el-icon-search"
						size="mini"
						v-model="tableSearchKey"
					>
					</el-input>
				</div>
        <div slot="btn-tools-right">
					<el-button class="order-btn" type="primary" size="mini">查询</el-button>
				</div>
			</w-table>
				</div>
		</div>
		<template slot="footer">
				<el-button @click="onCancelClick">取消</el-button>
				<fx-button type="save" @click="onSaveClick">保存</fx-button>
		</template>
	</w-dailog>
</template>
<script>
export default {
	name: '',
	data () {
		return {
			dialogVisible: false,
			tableColumn: [
				{
					prop: 'code',
					label: '生产计划单号',
					width: '130px',
					required: true
				},
				{ prop: 'productionPlanDate', label: '生产计划日期', width: '130px' },
				{
					prop: 'factoryName',
					label: '工厂',
					width: '130px',
					required: true
				}
			],
			detailsColumn: [
				{
					prop: 'materialCode',
					label: '产品编号',
					width: '100px',
					required: true
				},
				{ prop: 'materialName', label: '产品名称', width: '120px' },
				{
					prop: 'materialUnitName',
					label: '生产单位',
					width: '100px',
					required: true
				}
			],
			tableDetails: [],
			listSelRows: [],
			detailSelRows: [],
			keyWords: '',
			dateRange: [this.$fxUtils.setDate(new Date()), this.$fxUtils.setDate(new Date())],
			tableSearchKey: '',
			searchProps: ['code', 'materialCode', 'materialName']
		}
	},
	computed: {
		filterSelItem () {
			const filtrDetails = []
			this.tableDetails.forEach(program => {
				const item = program.detailList.filter(item => {
					return item.check === 1
				})
				const { id, factoryName, productionPlanDate, code } = program
				if (item.length > 0) {
					filtrDetails.push({
						id,
						factoryName,
						productionPlanDate,
						code,
						detailList: item
					})
				}
			})
			// const filtrDetails = this.tableDetails.filter(program => {
			// 	const item = program.detailList.filter(item => {
			// 		return item.check === 1
			// 	})
			// 	const { id, factoryName, productionPlanDate, code } = program
			// 	if (item.length > 0) {
			// 		return {
			// 			id,
			// 			factoryName,
			// 			productionPlanDate,
			// 			code,
			// 			detailList: item
			// 		}
			// 	}
			// })
			return filtrDetails.filter(item => {
				return this.$fxUtils.fuzzyQueryObj(item, this.tableSearchKey, this.searchProps)
			})
		},
		filterAllItems () {
			if (this.dateRange && this.dateRange.length > 0) {
				return this.tableDetails.filter(item => {
					return item.productionPlanDate >= this.dateRange[0] && item.productionPlanDate <= this.dateRange[1] && this.$fxUtils.fuzzyQueryObj(item, this.keyWords, this.searchProps)
				})
			} else {
				return this.tableDetails.filter(item => {
					return this.$fxUtils.fuzzyQueryObj(item, this.keyWords, this.searchProps)
				})
			}
		}
	},
	watch: {
		// 监听父表格选中
		listSelRows: {
			immediate: true,
			handler (programSelList) {
				// 从父表格选中的给子表格选中
				this.tableDetails.forEach(all => {
					all.detailSelRows = []
					all.detailList.forEach(d => {
						d.check = 0
					})
					programSelList.forEach(program => {
						program.detailList.forEach(d => {
							d.check = 1
						})
						program.detailSelRows = JSON.parse(JSON.stringify(program.detailList))
					})
				})
			}
		}
	},
	methods: {
		async open () {
			this.dateRange = [this.$fxUtils.setDate(new Date()), this.$fxUtils.setDate(new Date())]
			const programList = await this.getProgramList()
			programList.forEach(item => {
				item.detailSelRows = []
				item.detailList.forEach(_item => {
					_item.id = _item.detailId
				})
			})
			this.tableDetails = programList
			this.dialogVisible = true
			// 清空选中
			if (this.$refs.listTableUnImport) {
				this.$refs.listTableUnImport.selectedArr = []
				// this.tableDetails.forEach(item => {
				// 	this.$refs.listTableUnImport.$refs.organTable.toggleRowExpansion(item, false)
				// })
			}
		},
		// 获取生产计划明细
		async getProgramList () {
			return this.$fxApi('schedule.findExportPlanDataList').then(programList => {
				return programList
			})
		},
		onTableRowSelect (row, flag) {
			this.$nextTick(() => {
				// 先找到勾选物料在当前计划中的序号
				const program = this.tableDetails.filter(p => {
					return p.id === row.pid
				})
				if (flag) {
					const leftIndex = this.$refs.listTableUnImport.selectedArr.findIndex(selectItem => {
						return selectItem === program[0].id
					})
					if (leftIndex === -1) {
						this.$refs.listTableUnImport.selectedArr.push(program[0].id)
						this.$refs.listTableUnImport.$refs.organTable.toggleRowSelection(program[0], true)
					}
					this.checkSingleDetail(row, 1)
				} else {
					this.checkSingleDetail(row, 0)
					// 如果物料都没有选中 就把计划取消勾选
					const isAllUnCheck = program[0].detailList.every(item => {
						return item.check === 0
					})
					const leftIndex = this.$refs.listTableUnImport.selectedArr.findIndex(selectItem => {
						return selectItem === program[0].id
					})
					if (isAllUnCheck) {
						this.$refs.listTableUnImport.$refs.organTable.toggleRowSelection(program[0], false)
						if (leftIndex !== -1) {
							this.$refs.listTableUnImport.selectedArr.splice(leftIndex)
						}
					}
				}
			})
		},
		onTableRowAllSelect (selecteds) {
			this.$nextTick(() => {
				const selProgram = this.tableDetails.filter(p => {
					return p.detailSelRows.length > 0
				})
				if (selProgram.length === 0) {
					this.$refs.listTableUnImport.selectedArr = []
					this.$nextTick(() => {
						this.$refs.listTableUnImport.$refs.organTable.clearSelection()
						this.tableDetails.forEach(item => {
							this.$refs.listTableUnImport.$refs.organTable.toggleRowSelection(item, false)
						})
					})
					this.checkAllDetails(0)
				} else {
					const selIds = selProgram.map(p => {
						return p.id
					})
					this.tableDetails.forEach(p => {
						const flag = selIds.includes(p.id)
						if (!flag) {
							this.$refs.listTableUnImport.$refs.organTable.toggleRowSelection(p, false)
							this.checkProgramDetails(p, 0)
						} else {
							this.$refs.listTableUnImport.$refs.organTable.toggleRowSelection(p, true)
							this.checkProgramDetails(p, 1)
						}
					})
				}
			})
		},
		// 给details中的check赋值
		checkAllDetails (check) {
			this.tableDetails.forEach((program, i) => {
				program.detailList.forEach(item => {
					item.check = check
				})
			})
		},
		checkProgramDetails (row, check) {
			this.tableDetails.forEach((program, i) => {
				if (row.id === program.id) {
					program.detailList.forEach(item => {
						item.check = check
					})
				}
			})
		},
		checkSingleDetail (row, check) {
			this.tableDetails.forEach((program, i) => {
				if (program.id === row.pid) {
					program.detailList.forEach(item => {
						if (item.id === row.id) {
							item.check = check
						}
					})
				}
			})
		},
		// 保存按钮
		onSaveClick () {
			if (this.filterSelItem.length === 0) {
				const error = '请选择一条明细'
				this.$fxMessage.warning(error)
				return false
			}
			this.doSaveHandleClick()
		},
		doSaveHandleClick () {
			const postData = {
				productionPlanIds: [],
				detailIds: []
			}
			this.filterSelItem.forEach(program => {
				postData.productionPlanIds.push(program.id)
				program.detailList.forEach(item => {
					postData.detailIds.push({
						detailId: item.detailId,
						productionPlanId: item.pid
					})
				})
			})
			return this.$fxApi('schedule.saveOrUpdateProcedureTask')({
				data: postData
			}).then(res => {
				this.dialogVisible = false
				this.$emit('on-refresh')
			})
		},
		onCancelClick () {
			this.dialogVisible = false
			this.$emit('on-refresh')
		},
		resetSearch () {
			this.dateRange = []
			this.keyWords = ''
		}
	}
}
</script>
<style lang="stylus" scoped>
@import '~$assets/stylus/varsty.styl'
.fx-import {
	display: flex;
	flex-direction: row;
	flex: 1;
	.list-container {
		flex: 1
		overflow:auto
		display: flex;
		flex-direction: column;
	}
	.tools-container {
		display: flex
		flex-direction: column
		align-items: center
		justify-content: center
		width: 100px
		.tools-btn {
			width: 50px
			margin-top: 20px
			margin-left: 0
		}
	}
}
</style>
